import React, { useContext } from "react";
import classNames from "classnames";
import useStyles from "./styles";
import { ThemeContext } from "../../../theme";
import { Info } from "@ct0/icons";
import { Tooltip } from "../../../Tooltip";
import type { FormViewJustifyContent } from "../../type";

interface FieldProps {
  isLast?: boolean;
  label?: string;
  suffix?: string;
  required?: boolean;
  children?: React.ReactNode;
  errmsg?: string;
  labelWidth?: string | number;
  justifyContent?: FormViewJustifyContent;
  className?: string;
  slack?: boolean;
  labelTips?: React.ReactNode;
}

export default Field;

function Field({
  label,
  slack,
  isLast,
  suffix,
  required,
  errmsg,
  children,
  labelWidth,
  labelTips,
  justifyContent,
  className,
}: FieldProps) {
  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });

  const overlay =
    typeof labelTips == "string" ? (
      <div className={classes.overlay}>{labelTips}</div>
    ) : (
      labelTips
    );

  return (
    <div
      className={classNames([
        classes.item,
        justifyContent == "flex-end" && classes.flexEnd,
        justifyContent == "space-between" && classes.spaceBetween,
        slack && classes.slack,
        isLast && classes.lastItem,
        className,
      ])}
    >
      <div className="ct0-formview-item-label" style={{ width: labelWidth }}>
        {label && (
          <>
            <span className="ct0-formview-item-label-text">{label}</span>
            {required && <b className="ct0-formview-item-label-star">*</b>}
            {labelTips && (
              <Tooltip overlay={overlay}>
                <span className={classes.labelTips}>
                  <Info />
                </span>
              </Tooltip>
            )}
          </>
        )}
      </div>
      <div
        className={classNames(classes.input, !label && classes.inputNoLabel)}
      >
        {children}
        <div className="ct0-formview-item-error">{errmsg}</div>
        {suffix && <span className={classes.suffix}>{suffix}</span>}
      </div>
    </div>
  );
}
